/**
 * @Description: userReducer
 * @author zhaojiuyi
 * @date 2023/4/14
 */
import {ActionConfig} from "../actions/user.action";
import {LOGOUT, SET_TOKEN, SET_USERNAME} from "../constant";
import {Reducer} from "redux";

export interface UserStateConfig {
    token: string | null
    username: string | null
    avatar: string | null
}

const userState: UserStateConfig = {
    token: window.localStorage.getItem("token") || null,
    username: window.localStorage.getItem("username") || "🔥🔥🔥🔥",
    avatar: "/avatar.jpg"
}

/**
 * @Description: userReducer
 * @author zhaojiuyi
 * @date 2023/4/15
*/
export const userReducer:Reducer<UserStateConfig,ActionConfig> = (preState = userState, action: ActionConfig) => {
    let {type,data} = action
    let newState: UserStateConfig

    switch (type) {
        case SET_TOKEN:
            newState = setToken(preState,data)
            break
        case SET_USERNAME:
            newState = setUsername(preState,data)
            break
        case LOGOUT:
            newState = logOutHandler(preState)
            break
        default:
            newState = preState
    }
    return newState

}

/* 退出登录 */
function logOutHandler(preState: UserStateConfig):UserStateConfig {
    window.localStorage.removeItem("token")
    window.localStorage.removeItem("username")
    return {
        ...preState,
        token: null,
        username: null
    };
}

/*设置token*/
function setToken(preState: UserStateConfig, token: string) {
    window.localStorage.setItem("token", token)
    return {...preState,token}
}
/*设置用户名*/
function setUsername(preState: UserStateConfig, username: string) {
    window.localStorage.setItem("username", username)
    return {...preState,username}
}

